#include "Tools.h"

void Tools::Trim(std::string &str)
{
    str.erase(0, str.find_first_not_of(" "));
    str.erase(str.find_last_not_of("\r") + 1);
    str.erase(str.find_last_not_of(" ") + 1);
}

std::vector<std::string> Tools::Split(const std::string &str, char delimiter)
{
    std::vector<std::string> tokens;
    std::string token;
    std::istringstream tokenStream(str);
    while (std::getline(tokenStream, token, delimiter)) {
        tokens.push_back(token);
    }
    return tokens;
}

std::string Tools::GenRandom(const int len)
{
    std::stringstream ss;
    for (auto i = 0; i < len; i++) {
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<> dis(0, 255);
        const auto rc = dis(gen);
        std::stringstream hexstream;
        hexstream << std::hex << rc;
        auto hex = hexstream.str();
        ss << (hex.length() < 2 ? '0' + hex : hex);
    }
    return ss.str();
}

long Tools::GetEarliestTime(const std::string type)
{
    time_t now = time(nullptr);
    
    // 使用localtime函数将time_t类型转换成tm类型
    struct tm* localTime = localtime(&now);

    // 通过tm_year、tm_mon和tm_mday成员获取年、月、日
    int year = localTime->tm_year;
    int month = localTime->tm_mon;
    int day = localTime->tm_mday;

    struct tm timeinfo = {};
    timeinfo.tm_year = year;
    timeinfo.tm_isdst = -1;

    if(type == "Day" || type.empty())
    {
        timeinfo.tm_mon = month;
        timeinfo.tm_mday = day;
    }
    else if(type == "Month")
    {
        timeinfo.tm_mon = month;
        timeinfo.tm_mday = 1;
    }
    else
    {
        timeinfo.tm_mday = 1;
    }

    time_t timestamp = std::mktime(&timeinfo);

    return timestamp;
}